package com.cgc.venus.server.app.controller;

import com.cgc.venus.server.app.bean.*;
import com.cgc.venus.server.app.inter.AppManageService;
import com.cgc.venus.server.core.bean.response.VenusResponse;
import com.cgc.venus.server.core.bean.response.VenusResponseStatus;
import com.cgc.venus.server.core.exception.VenusException;
import com.cgc.venus.server.core.harbor.model.Project;
import com.cgc.venus.server.core.harbor.model.Repository;
import com.cgc.venus.server.core.utils.DateUtil;
import com.cgc.venus.server.core.utils.StringUtil;
import io.fabric8.kubernetes.api.model.extensions.Ingress;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.common.recycler.Recycler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.awt.font.FontRenderContext;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by xyr on 2017/6/3.
 * 应用中心-应用管理-控制层
 */
@Api(value = "应用管理",description="应用管理所对应服务的api")
@RequestMapping("/app-admin")
@RestController
public class AppController {

    @Autowired
    private AppManageService appManageService;

    @Autowired
    private AppManageConfigBean appManageConfigBean;

    /*
    * 验证应用名称是否存在
    * */
    @ApiOperation(value = "验证应用名称是否存在--接口", notes = "验证应用名称是否存在")
    @RequestMapping(value = "/app-name", method = RequestMethod.GET)
    public VenusResponse<Integer> validateAppName(@RequestParam("appName") String appName) throws VenusException {
        if (StringUtils.isBlank(appName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        int row = appManageService.validateAppName(appName);
        int code = row > 0 ? VenusResponseStatus.OK : VenusResponseStatus.HANDLE_ERROR;
        VenusResponse<Integer> response = new VenusResponse<Integer>(VenusResponseStatus.OK,"",code);
        return response;
    }

    /*
    * 应用创建-根据粘贴的yaml文件创建应用
    * */
    @ApiOperation(value = "应用创建-接口", notes = "根据粘贴的yaml文件创建应用")
    @RequestMapping(value = "/app-create/compose-file", method = RequestMethod.POST)
    public VenusResponse<Object> createAppByFileContent(@RequestBody AppManageBean appManageBean) throws VenusException{
        // 非空判断
        if (StringUtils.isBlank(appManageBean.getAppName()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(appManageBean.getNamespace()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名为空");
        if (StringUtils.isBlank(appManageBean.getDescribed()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用描述为空");
        if (StringUtils.isBlank(appManageBean.getFileData()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "文件内容为空");

        // 获得文件内容
        String yamlContent = appManageBean.getFileData();
        // 分割
        yamlContent = yamlContent.replaceAll("\r\n","\n");

        String[] yamlArr = yamlContent.split("---\n");
        int yamlArrLength = yamlArr.length;

        StringBuilder sb = new StringBuilder();

        // 创建
        for (int i = 0; i < yamlArrLength; i++) {

            if (StringUtils.isBlank(yamlArr[i])) continue;
            // 接口调用
            String message = appManageService.createAppByYaml(appManageBean,yamlArr[i]);
            // 应用创建失败,记录返回信息
            if (StringUtils.isNotBlank(message)) {
                sb.append(message).append(";").append("\n");
            }
        }

        // 返回客户端内容
        Map<String,Object> map = new HashMap<String, Object>();
        int statusCode = StringUtils.isBlank(sb.toString()) ? VenusResponseStatus.OK : VenusResponseStatus.HANDLE_ERROR;
        map.put("statusCode",statusCode);
        map.put("message",sb.toString());

        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",map);
        return response;
    }

    /*
    * 应用创建-根据上传的yaml文件创建应用
    * */
    @ApiOperation(value = "应用创建-接口", notes = "根据上传的yaml文件创建应用")
    @RequestMapping(value = "/app-create/upload-file", method = RequestMethod.POST)
    public VenusResponse<Object> createAppByUploadFile(HttpServletRequest request) throws VenusException{
        // 此接口支持上传多文件
        List<MultipartFile> multipartFileList = ((MultipartHttpServletRequest) request).getFiles("file");
        StringBuilder sb = new StringBuilder();
        try {
            // 得到表单数据
            Map<String,String[]> map = request.getParameterMap();
            String currentNamespace = map.get("namespace")[0];
            AppManageBean appManageBean = new AppManageBean();
            appManageBean.setAppName(map.get("appName")[0]);
            appManageBean.setDeployType(0);
            appManageBean.setDescribed(map.get("described")[0]);
            appManageBean.setNamespace(currentNamespace);

            for (MultipartFile file1 : multipartFileList) {
                // 得到文件内容
                String fileContent = new String(file1.getBytes(),"utf-8");
                // 分割
                fileContent = fileContent.replaceAll("\r\n","\n");

                String[] arr = fileContent.split("---\n");
                int arrLength = arr.length;

                for (int j = 0; j < arrLength; j++) {
                    String yamlStr = arr[j];
                    if (StringUtils.isBlank(yamlStr)) continue;

                    // 获得空间名字
                    String namespaceInYaml = AppManageConfigBean.getValueFromYaml(yamlStr,"namespace:","\n");

                    // yaml文件的空间名称和当前的空间名称是否一直
                    // 只能在客户当前选择空间创建应用

                    if (namespaceInYaml.indexOf(currentNamespace) == -1) {
                        String kind = AppManageConfigBean.getValueFromYaml(yamlStr,"kind:","\n").replaceAll("kind:","").trim();
                        String appNameKube = AppManageConfigBean.getValueFromYaml(yamlStr,"name:","\n").replaceAll("name:","").trim();
                        sb.append(kind).append(" ").append(appNameKube).
                                append("没有权限在:").append(currentNamespace).append("空间中创建").append("\n");
                        continue;
                    }

                    String message = appManageService.createAppByYaml(appManageBean,yamlStr);
                    if (StringUtils.isNotBlank(message)) {
                        sb.append(message).append(",").append("\n");
                    }
                }

            }

        } catch (Exception e) {
            throw new VenusException(VenusResponseStatus.HANDLE_ERROR,"创建应用失败");
        }

        Map<String,Object> map = new HashMap<String, Object>();
        int statusCode = StringUtils.isBlank(sb.toString()) ? VenusResponseStatus.OK : VenusResponseStatus.HANDLE_ERROR;
        map.put("statusCode",statusCode);
        map.put("message",sb.toString());

        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"成功创建应用",map);
        return response;
    }

    /*
    * 应用查询-根据查询关键字,查询应用状态获得查询列表,分页
    * */
    @ApiOperation(value = "应用查询--接口", notes = "根据查询关键字,查询应用状态获得查询列表")
    @RequestMapping(value = "/app-list", method = RequestMethod.GET)
    public VenusResponse<Object> queryApps(@RequestParam("page") int page,@RequestParam("pageSize") int pageSize,
                                           @RequestParam("queryKey") String queryKey, @RequestParam("queryStatus") String queryStatus,
                                           @RequestParam("namespace") String namespace) throws VenusException{
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名为空");
        List<AppManageBean> getAppManageBeanList = new ArrayList<AppManageBean>();
        Long total = 0L;

        List<AppManageBean> reAppManageBeanList = new ArrayList<AppManageBean>();

        // 1:查询所有
        getAppManageBeanList = appManageService.queryApps(page,pageSize,queryKey,queryStatus,namespace);
        // 2:调用k8s接口,获得实例数,状态
        int mapListSize = getAppManageBeanList.size();
        if (mapListSize > 0) {
            total = appManageService.countApps(queryKey,namespace);
            for (int i = 0; i < mapListSize; i++) {
                AppManageBean appManageBean = getAppManageBeanList.get(i);
                String appKind = appManageBean.getAppKind();
                // 实例数 可用副本/总的副本
                String replicas = appManageService.getReplicasByKind(appKind,appManageBean.getNamespace(),appManageBean.getAppNameKube());

                if (StringUtils.isBlank(replicas)) continue;

                // 得到状态
                String status = appManageService.getAppStatus(replicas,appManageBean.getTimeDiff());
                appManageBean.setReplicas(replicas);
                appManageBean.setStatus(status);

                reAppManageBeanList.add(appManageBean);
            }

        }

        // 筛选状态
        if (!"all".equals(queryStatus)) {
            String status = "";
            if (AppManageConfigBean.APP_STATUS_RUNNING_EN.equals(queryStatus)) {
                status = AppManageConfigBean.APP_STATUS_RUNNING;
            } else if (AppManageConfigBean.APP_STATUS_CLOSE_EN.equals(queryStatus)) {
                status = AppManageConfigBean.APP_STATUS_CLOSE;
            } else if (AppManageConfigBean.APP_STATUS_ERROR_EN.equals(queryStatus)) {
                status = AppManageConfigBean.APP_STATUS_ERROR;
            }
            /*List<AppManageBean> statusAppList = new ArrayList<AppManageBean>();
            for (int i = 0; i <total; i++) {
                AppManageBean app = reAppManageBeanList.get(i);
                String status_temp = app.getStatus();
                if (status_temp.equals(status)) {
                    statusAppList.add(app);
                }
            }*/

            if (reAppManageBeanList.size() > 0) {
                final String s = status;
                reAppManageBeanList = reAppManageBeanList.stream().filter(appManageBean -> appManageBean.getStatus().indexOf(s) != -1).collect(Collectors.toList());
                total = Long.valueOf(reAppManageBeanList.size());
            }

            // 总数
            /*total = Long.valueOf(statusAppList.size());
            reAppManageBeanList.clear();
            reAppManageBeanList = statusAppList;*/

        }

        Map<String,Object> map = new HashMap<String, Object>();
        map.put("total",total);
        map.put("items",reAppManageBeanList);

        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",map);
        return response;
    }

    /*
    * 超级管理员工,获取所有应用
    * */
    @ApiOperation(value = "查询所有命名空间中的应用--接口", notes = "查询所有命名空间中的应用")
    @RequestMapping(value = "/app-count", method = RequestMethod.GET)
    public VenusResponse<Object> getAllApp(@RequestParam(value="namespace",required = false) String namespace) throws VenusException {
        int total_running = 0;
        int total_error = 0;
        int total_close = 0;
        // 从数据库库中得到所有的应用信息
        List<AppManageBean> appManageBeanList = new ArrayList<AppManageBean>();
        List<AppManageBean> getAppManageBeanList = new ArrayList<>();
        if (StringUtils.isNotBlank(namespace)) {
            // 根据命名空间查询
            getAppManageBeanList = appManageService.queryApps(1,1000000,"","all",namespace);
        } else {
            // 查询全部
            getAppManageBeanList = appManageService.getAllApp();
        }

        // 从k8s集群中得到应用的状态信息
//        if (getAppManageBeanList.size() > 0) {
//            getAppManageBeanList.forEach(appManageBean -> {
//                try {
//                    // 获取实例数
//                    String replicas = appManageService.getReplicasByKind(appManageBean.getAppKind(),appManageBean.getNamespace(),appManageBean.getAppNameKube());
//                    // 获取状态
//                    String status = appManageService.getAppStatus(replicas,appManageBean.getTimeDiff());
//                    appManageBean.setReplicas(replicas);
//                    appManageBean.setStatus(status);
//                    appManageBeanList.add(appManageBean);
//                } catch (VenusException e) {
//                }
//            });
//        }

        for (AppManageBean appManageBean : getAppManageBeanList) {
            String replicas = appManageService.getReplicasByKind(appManageBean.getAppKind(),appManageBean.getNamespace(),appManageBean.getAppNameKube());
            String status = appManageService.getAppStatus(replicas,appManageBean.getTimeDiff());
            appManageBean.setStatus(status);
            appManageBean.setReplicas(replicas);
            if (AppManageConfigBean.APP_STATUS_RUNNING.equals(status)) {
                total_running++;
            } else if (AppManageConfigBean.APP_STATUS_ERROR.equals(status)) {
                total_error++;
            } else if (AppManageConfigBean.APP_STATUS_CLOSE.equals(status)) {
                total_close++;
            }
            appManageBeanList.add(appManageBean);
        }

        Map<String,Object> map = new HashMap<String,Object>();
        map.put("total",appManageBeanList.size());
        map.put("total_error",total_error);
        map.put("total_running",total_running);
        map.put("total_close",total_close);
        map.put("items",appManageBeanList);
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",map);
        return response;
    }

    /*
    * 根据应用ID,获得应用信息
    * */
    @ApiOperation(value = "获取应用信息--接口", notes = "根据应用ID,获取应用信息")
    @RequestMapping(value = "/app-detailed/{appId}", method = RequestMethod.GET)
    public VenusResponse<AppManageBean> getAppBaseById(@PathVariable("appId") String appId) throws VenusException{
        if (StringUtils.isBlank(appId))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用ID为空");

        // 1: 先从数据库获得,应用的基本信息
        AppManageBean appManageBean = appManageService.getAppManageBeanById(appId);

        // 2: 从kubernetes 接口获得应用实时的状态,实例等
        String appKind = appManageBean.getAppKind();
        String namespace = appManageBean.getNamespace();
        String appNameKube = appManageBean.getAppNameKube();

        // 获取应用实例
        String replicas = appManageService.getReplicasByKind(appKind,namespace,appNameKube);

        //add by 业哥 180511  start
        appManageService.getAppBaseInfo(appKind, namespace, appNameKube, appManageBean);
        //add by 业哥 180511  end


        // 获取应用状态
        String fromTime = appManageBean.getCreateTime();
        String toTime = DateUtil.getCurrentTime(DateUtil.yyyy_MM_dd_HH_mm_ss);
        String timeDiff = DateUtil.getTimeDifference(DateUtil.yyyy_MM_dd_HH_mm_ss,fromTime,toTime);
        String status = appManageService.getAppStatus(replicas,timeDiff);

        // 获取当前应用是否开启自动伸缩功能
        boolean ishpa = appManageService.autoScale(namespace,AppManageConfigBean.getHpaName(appNameKube));
        if (ishpa) {
            appManageBean.setAutoScale(true);
        }

        // 获取应用的服务地址
        //List<Map<String, Object>> appServiceAddressList = appManageService.getServiceAddress(namespace,AppManageConfigBean.getServiceName(appNameKube));
        List<Map<String, Object>> appServiceAddressList = appManageService.getServiceAddressByLabels(namespace,appNameKube);
        appManageBean.setAppServiceAddressList(appServiceAddressList);

        // 设置
        appManageBean.setReplicas(replicas);
        appManageBean.setStatus(status);

        VenusResponse<AppManageBean> response = new VenusResponse<AppManageBean>(VenusResponseStatus.OK,"",appManageBean);
        return response;
    }

    /*
    * 根据应用空间,应用名称,获取pod信息
    * */
    @ApiOperation(value = "获取pod信息--接口", notes = "根据空间名称,应用ID")
    @RequestMapping(value = "/pod-list/{namespace}/{appId}", method = RequestMethod.GET)
    public VenusResponse<List<AppManageBean>> getPodByAppId(@PathVariable("namespace") String namespace,@PathVariable("appId") String appId) throws VenusException {

        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appId))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用id为空");
        // 从数据库中获取当前应用的信息
        AppManageBean appManageBean = appManageService.getAppManageBeanById(appId);
        // 从k8s api server中得到pod list信息
        //List<AppManageBean> appManageBeanList = appManageService.getPodStatus(namespace,appManageBean.getAppNameKube());
        List<AppManageBean> appManageBeanList = appManageService.getPodListWithLabel(namespace,appManageBean.getAppNameKube());

        VenusResponse<List<AppManageBean>> response = new VenusResponse<List<AppManageBean>>(VenusResponseStatus.OK,"",appManageBeanList);

        return response;
    }

    /*
    * 根据应用空间,应用名称,获取pod信息
    * */
    @ApiOperation(value = "获取pod信息--接口", notes = "根据空间名称,应用英文名称")
    @RequestMapping(value = "/pod-list", method = RequestMethod.GET)
    public VenusResponse<List<AppManageBean>> getPodByAppName(@RequestParam("namespace") String namespace,@RequestParam("appKubeName") String appKubeName) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appKubeName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        List<AppManageBean> appManageBeanList = appManageService.getPodListWithLabel(namespace,appKubeName);
        VenusResponse<List<AppManageBean>> response = new VenusResponse<List<AppManageBean>>(VenusResponseStatus.OK,"",appManageBeanList);
        return response;
    }


    /*
    * 水平伸缩应用,根据应用所属空间名,应用类型,应用名称,伸缩实例数
    *   目前只针对两种资源对象伸缩实例
    *    deployment statefulSet
    * */
    @ApiOperation(value = "水平伸缩应用--接口", notes = "根据应用所属空间名,应用类型,应用名称,伸缩实例数")
    @RequestMapping(value = "/horizontal-scale", method = RequestMethod.PATCH)
    public VenusResponse<String> horizontalScalingApp(@RequestBody AppManageBean appManageBean) throws VenusException {
        String namespace = appManageBean.getNamespace();
        String appNameKube = appManageBean.getAppNameKube();
        String appKind = appManageBean.getAppKind();
        String replicas_str = appManageBean.getReplicas();
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(appKind))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空");
        if (StringUtils.isBlank(replicas_str))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "伸缩实例数为空");

        int replicas = Integer.valueOf(replicas_str);
        int replicas_re = 0;
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            replicas_re = appManageService.horizontalScalingDeployment(namespace,appNameKube,replicas);
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            replicas_re = appManageService.horizontalScalingStatefulSet(namespace,appNameKube,replicas);
        }

        String message = "水平扩展实例,失败";
        if (replicas == replicas_re) {
            message = "水平扩展实例,成功,容器组在5秒后刷新";
            // 更新数据库
            appManageService.updateAppLastTime(appManageBean.getId());
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }


    /*
    * 灰度升级,获取当前应用,所使用的镜像名称,以及版本列表
    * */
    @ApiOperation(value = "灰度升级,获取当前应用,所使用的镜像名称,以及版本列表--接口", notes = "根据镜像名称")
    @RequestMapping(value = "/image-tag", method = RequestMethod.GET)
    public VenusResponse<Object> getAppImageVersionTag(@RequestParam("imageName") String imageName) throws VenusException {
        //String imageName = appManageBean.getImageName();
        if (StringUtils.isBlank(imageName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空");
        List<com.cgc.venus.server.core.harbor.model.Tag> list = appManageService.getRepositorieTags(imageName);
        //list 排序 倒序+取5条记录
        Comparator<com.cgc.venus.server.core.harbor.model.Tag> comparator = (h1, h2) -> h1.getCreated().compareTo(h2.getCreated());
        list.sort(comparator.reversed());
        int len=list.size();
        int index=5;
        if(len<5){
            index=len;
        }
        //list 排序 倒序+取5条记录
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",list.subList(0,index));
        return response;
    }

    /*
    * 灰度升级,根据应用所属空间名,应用类型,应用名称,镜像版本号
    *   目前只针对两种资源对象伸缩实例
    *    deployment statefulSet
    * */
    @ApiOperation(value = "灰度升级--接口", notes = "根据应用所属空间名,应用类型,应用名称,镜像名称,目标镜像版本")
    @RequestMapping(value = "/gray-update", method = RequestMethod.PATCH)
    public VenusResponse<String> grayUpdateApp(@RequestBody AppManageBean appManageBean) throws VenusException {
        String namespace = appManageBean.getNamespace();
        String appNameKube = appManageBean.getAppNameKube();
        String appKind = appManageBean.getAppKind();
        String imageName = appManageBean.getImageName();
        String targetImageVersion = appManageBean.getTargetImageVersion();
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(appKind))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空");
        if (StringUtils.isBlank(imageName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空");
        if (StringUtils.isBlank(targetImageVersion))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "目标镜像版本为空");

        boolean update = false;
        String targetImage =appManageConfigBean.getHarborUrl() +"/"+ imageName + ":" +targetImageVersion;
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            update = appManageService.updateDeployment(namespace,appNameKube,targetImage);
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            update = appManageService.updateStatefunSet(namespace,appNameKube,targetImage);
        } else if (AppManageConfigBean.Kind_DaemonSet.indexOf(appKind) != -1) {
            update = appManageService.updateDaemonSet(namespace,appNameKube,targetImage);
        }

        String message = appManageBean.getAppName() + "灰度升级,失败";
        if (update) {
            message = appManageBean.getAppName() + "灰度升级,成功,容器组在5秒后刷新";
            // 更新数据库,应用的版本号
            appManageService.updateAppImageVersion(targetImageVersion,appManageBean.getId());
        }

        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }


    /*
    * 获取应用自动伸缩设置的参数
    * */
    @ApiOperation(value = "获取应用自动伸缩设置的参数--接口", notes = "根据应用所属空间名,应用名")
    @RequestMapping(value = "/hpa-detailed/{namespace}/{appNameKube}", method = RequestMethod.GET)
    public VenusResponse<Object> getAppHpa(@PathVariable("namespace")String namespace, @PathVariable("appNameKube") String appNameKube) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        AppManageHpaBean map = appManageService.getAppHpa(namespace,appNameKube);
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",map);
        return response;
    }

    /*
    * 新增应用,自动伸缩功能
    * */
    @ApiOperation(value = "新增应用,自动伸缩功能--接口", notes = "新增应用,自动伸缩功能")
    @RequestMapping(value = "/auto-scale", method = RequestMethod.POST)
    public VenusResponse<String> addAutoScaleToApp(@RequestBody AppManageHpaBean appManageHpaBean) throws VenusException {
        if (StringUtils.isBlank(appManageHpaBean.getNamespace()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appManageHpaBean.getAppNameKube()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称(k8s)为空");
        boolean flag = appManageService.addAutoScaleToApp(appManageHpaBean);
        String message = appManageHpaBean.getAppName() +",新增自动伸缩功能,失败";
        if (flag) {
            message = appManageHpaBean.getAppName() +",新增自动伸缩功能,成功,容器组在5秒后刷新";
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }

    /*
    * 修改应用,自动伸缩参数设置
    * */
    @ApiOperation(value = "修改应用,自动伸缩参数设置--接口", notes = "修改应用,自动伸缩参数设置")
    @RequestMapping(value = "/auto-scale", method = RequestMethod.PATCH)
    public VenusResponse<String> editAutoScaleToApp(@RequestBody AppManageHpaBean appManageHpaBean) throws VenusException {
        if (StringUtils.isBlank(appManageHpaBean.getNamespace()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(appManageHpaBean.getAppNameKube()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称(k8s)为空");
        boolean flag = appManageService.editAutoScaleToApp(appManageHpaBean);
        String message = appManageHpaBean.getAppName() +",修改自动伸缩功能,失败";
        if (flag) {
            message = appManageHpaBean.getAppName() +",修改自动伸缩功能,成功,容器组在5秒后刷新";
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }

    /*
    * 删除应用,自动伸缩功能
    * */
    @ApiOperation(value = "删除应用,自动伸缩功能--接口", notes = "删除应用,自动伸缩功能")
    @RequestMapping(value = "/auto-scale/{namespace}/{appNameKube}", method = RequestMethod.DELETE)
    public VenusResponse<String> deleteAutoScaleToApp(@PathVariable("namespace") String namespace,@PathVariable("appNameKube") String appNameKube) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "所属空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用的名称(k8s)为空");
        boolean flag = appManageService.deleteAutoScaleToApp(namespace,appNameKube);
        String message = "删除自动伸缩功能,失败";
        if (flag) {
            message = "删除自动伸缩功能,成功";
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }

    /*
    * 删除当前应用
    * */
    @ApiOperation(value = "删除当前应用--接口", notes = "删除当前应用,根据应用ID")
    @RequestMapping(value = "/app/{appId}", method = RequestMethod.DELETE)
    public VenusResponse<String> deleteAppById(@PathVariable("appId") String appId) throws VenusException {
        if (StringUtils.isBlank(appId))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用ID为空");

        // 根据当前应用ID,获取应用信息
        AppManageBean appManageBean = appManageService.getAppManageBeanById(appId);

        String appKind = appManageBean.getAppKind();
        String namespace = appManageBean.getNamespace();
        String appNameKube = appManageBean.getAppNameKube();

        // 先删除k8s,里面的应用
        boolean flag = appManageService.deleteAppInK8s(appKind,namespace,appNameKube);
        String message = "删除应用:" + appManageBean.getAppName() + ",失败";
        if (flag) {
            message = "删除应用:" + appManageBean.getAppName() + ",成功";
            // 删除数据库记录
            appManageService.deleteApp(appManageBean.getId());
            // 删除应用的服务资源
            appManageService.deleteService(appNameKube,namespace);
            // 删除k8singress
            appManageService.deleteIngress(namespace,appNameKube);
            // 删除数据库域名记录
            appManageService.deleteDomainName(namespace,appNameKube);
            // 删除hpa
            appManageService.deleteHPAByLabels(namespace,appNameKube);
        }

        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }

    /*
    * 删除pod
    * */
    @ApiOperation(value = "删除pod--接口", notes = "删除pod")
    @RequestMapping(value = "/pod/{namespace}/{appNameKube}", method = RequestMethod.DELETE)
    public VenusResponse<String> reStartPod(@PathVariable("namespace") String namespace, @PathVariable("appNameKube") String appNameKube) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "pod所属空间名为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "pod名称为空");
        boolean flag = appManageService.deletePod(namespace,appNameKube);
        String message = "应用:" + appNameKube + ",重新分配,失败";
        if (flag) {
            message = "应用:" +appNameKube + ",重新分配,成功";
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }


    /*
    * 重新部署,应用
    * */
    @ApiOperation(value = "重新部署,应用--接口", notes = "重新部署,应用")
    @RequestMapping(value = "/app", method = RequestMethod.PATCH)
    public VenusResponse<String> reDeployApp(@RequestBody AppManageBean appManageBean) throws VenusException {
        String namespace = appManageBean.getNamespace();
        String appNameKube = appManageBean.getAppNameKube();
        String replicas_str = appManageBean.getReplicas();
        String appKind = appManageBean.getAppKind();
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(replicas_str))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用实例个数为空");
        if (StringUtils.isBlank(appKind))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空");

        // 重新部署应用逻辑是:
        // 先将应用实例数---> 0
        // 再将应用扩展到指定实例数量
        String message ="应用:" + appManageBean.getAppName() + ",重新部署,失败";
        int targetReplicas = Integer.valueOf(replicas_str.split("/")[1]);
        /*int currentReplicas = 0;
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1 ) {
            currentReplicas = appManageService.horizontalScalingDeployment(namespace,appNameKube,0);
            if (currentReplicas == 0) {
                currentReplicas = appManageService.horizontalScalingDeployment(namespace,appNameKube,targetReplicas);
            }
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            currentReplicas = appManageService.horizontalScalingStatefulSet(namespace,appNameKube,0);
            if (currentReplicas == 0) {
                currentReplicas = appManageService.horizontalScalingStatefulSet(namespace,appNameKube,targetReplicas);
            }
        }*/
        int  currentReplicas = appManageService.reDeployApp(appKind,namespace,appNameKube,targetReplicas);

        if (targetReplicas == currentReplicas) {
            message ="应用:" + appManageBean.getAppName() + ",重新部署,成功";
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;

    }

    /*
    * 修改应用描述
    * */
    @ApiOperation(value = "修改应用描述--接口", notes = "修改应用描述")
    @RequestMapping(value = "/app-described", method = RequestMethod.PATCH)
    public VenusResponse<String> editAppDescribed(@RequestBody AppManageBean appManageBean) throws VenusException {
        String appId = appManageBean.getId();
        String described = appManageBean.getDescribed();
        if (StringUtils.isBlank(appId))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用ID为空");
        if (StringUtils.isBlank(described))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用描述为空");

        int row = appManageService.editAppDescribed(appId,described);

        String message = "修改应用描述:" + appManageBean.getAppName() + ",失败";
        if (row > 0) {
            message = "修改应用描述:" + appManageBean.getAppName() + ",成功";
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }

   /*
   * 根据pod名称,获取对应事件详细
   * */
   @ApiOperation(value = "根据pod名称,获取对应事件详细--接口", notes = "根据pod名称,获取对应事件详细")
   @RequestMapping(value = "/pod-events/{namespace}/{podName}", method = RequestMethod.GET)
   public VenusResponse<List<AppManageEventBean>> getPodEvents(@PathVariable("namespace") String namespace, @PathVariable("podName") String podName) throws VenusException {
       if (StringUtils.isBlank(namespace))
           throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
       if (StringUtils.isBlank(podName))
           throw new VenusException(VenusResponseStatus.NO_CONTENT, "pod名称为空");
       List<AppManageEventBean> eventBeans = appManageService.getPodEvents(namespace,podName);
       VenusResponse<List<AppManageEventBean>> response = new VenusResponse<List<AppManageEventBean>>(VenusResponseStatus.OK,"",eventBeans);
       return response;
   }

   /*
   * 根据空间名称,应用名称,获取pod 名称列表
   * */
   @ApiOperation(value = "根据空间名称,应用名称,获取pod 名称列表--接口", notes = "根据空间名称,应用名称,获取pod名称列表")
   @RequestMapping(value = "/pod-names/{namespace}/{appNameKube}", method = RequestMethod.GET)
   public VenusResponse<List<String>> getPodNames(@PathVariable("namespace") String namespace,@PathVariable("appNameKube") String appNameKube) throws VenusException {
       if (StringUtils.isBlank(namespace))
           throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
       if (StringUtils.isBlank(appNameKube))
           throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
       List<String> podNames = appManageService.getPodNames(namespace,appNameKube);
       VenusResponse<List<String>> response = new VenusResponse<>(VenusResponseStatus.OK,"",podNames);
       return response;
   }


    /*
    * 通过镜像仓库部署应用时候,根据项目名称,仓库类型,获取镜像列表,选择部署的镜像
    * */
    @ApiOperation(value = "通过镜像仓库部署应用时候,获取镜像列表,选择部署的镜像--接口", notes = "项目名称")
    @RequestMapping(value = "/project-images", method = RequestMethod.GET)
    public VenusResponse<Object> getProjectImages(@RequestParam("projectName") String projectName,@RequestParam(value = "queryKey", required = false) String queryKey) throws VenusException {
        if (StringUtils.isBlank(projectName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "项目名称为空");
        List<Repository> projectList = new ArrayList<Repository>();



        if (AppManageConfigBean.PUBLIC_WAREHOUSE.equals(projectName)) {
            // 将数据库中的公开镜像查询出来
            projectList = appManageService.getPublicImages();
        } else if (AppManageConfigBean.STORE_WAREHOUSE.equals(projectName)) {
            // 得到商店中镜像
            projectList = appManageService.getSoreImages();
        } else {
            projectList = appManageService.getProjectImages(projectName);
        }

        // 过滤
        if (StringUtils.isNotBlank(queryKey)) {
            projectList = projectList.stream().filter(repository -> repository.getRepositoryName().indexOf(queryKey) != -1).collect(Collectors.toList());
        }


        VenusResponse<Object> response = new VenusResponse<>(VenusResponseStatus.OK,"",projectList);
        return response;
    }


    /*
    * 根据镜像名称,获取镜像属性信息,包括: 基本信息,端口列表,环境变量信息,配置卷列表,高可用信息
    * */
    @ApiOperation(value = "根据镜像名称,获取镜像属性信息--接口", notes = "基本信息,端口列表,环境变量信息,配置卷列表,高可用信息")
    @RequestMapping(value = "/image-base", method = RequestMethod.GET)
    public VenusResponse<Object> getImageBase(@RequestParam("imageName") String imageName) throws VenusException {
        if (StringUtils.isBlank(imageName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空");
        Map<String,Object> responseData = new HashMap<>();
        // 基本信息表
        ImageBaseBean imageBaseMap = appManageService.getImageBase(imageName);


        // 端口列表
        List<Map<String,Object>> imagePortList = appManageService.getImagePortList(imageName);

        // 环境变量列表
        List<Map<String,Object>> imageEnvList = appManageService.getImageEnvList(imageName);

        // 配置卷列表
        List<Map<String,Object>> imageConfigVolumesList = appManageService.getImageConfigVolumes(imageName);
        //List<Map<String,Object>> imageConfigVolumesList = new ArrayList<Map<String,Object>>();

        // 高可用信息
        ImageHighAvailabilityBean imageHA = appManageService.getImageHABean(imageName);

        // 镜像启动参数
        List<Map<String,Object>> argsList = appManageService.getImageArgsList(imageName);

        if (imageBaseMap == null) {
            imageBaseMap = new ImageBaseBean();
            imageBaseMap.setImage(imageName);
        }

        if (imageHA == null) {
            imageHA = new ImageHighAvailabilityBean();
            imageHA.setImage(imageName);
        }

        responseData.put("imageHA",imageHA);
        responseData.put("imageBase",imageBaseMap);
        responseData.put("portDataList",imagePortList);
        responseData.put("envDataList",imageEnvList);
        responseData.put("configVolumesDataList",imageConfigVolumesList);
        responseData.put("commandArgs",argsList);

        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",responseData);
        return response;
    }

    /*
    * 设置镜像参数
    * */
    @ApiOperation(value = "设置镜像参数--接口", notes = "设置镜像参数")
    @RequestMapping(value = "/image-base", method = RequestMethod.PATCH)
    public VenusResponse<Object> setImageParam(@RequestBody ImageDataBean imageDataBean) throws VenusException {
        ImageBaseBean imageBaseBean = imageDataBean.getImageBase();
        String imageName = imageBaseBean.getImage();
        if (StringUtils.isBlank(imageName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像名称为空");

        // 1: 处理镜像基本信息
        ImageBaseBean reImageBaseMap = appManageService.getImageBase(imageName);
        int row = 0;
        if (reImageBaseMap == null) {
            // 新增
            row = appManageService.addImageBase(imageBaseBean);
        } else {
            // 修改
            row = appManageService.editImageBse(imageBaseBean);
        }

        // 2: 处理端口信息
        List<ImagePortBean> imagePortBeanList = imageDataBean.getImagePortList();
        int imagePortBeanListSize = imagePortBeanList.size();
        if (imagePortBeanListSize > 0) {
            appManageService.handleImagePort(imagePortBeanList,imageName);
        }

        // 3: 处理环境变量信息
        List<ImageEnvBean> imageEnvBeanList = imageDataBean.getImageEnvList();
        int imageEnvBeanListSize = imageEnvBeanList.size();
        if (imageEnvBeanListSize > 0) {
            appManageService.handleImageEnv(imageEnvBeanList,imageName);
        }

        // 4: 处理配置卷信息
        List<ImageConfigVolumesBean> imageConfigVolumesBeanList = imageDataBean.getImageConfigVolumesList();
        int imageConfigVolumesBeanListSize = imageConfigVolumesBeanList.size();
        if (imageConfigVolumesBeanListSize > 0) {
            appManageService.handleImageConfigVolumes(imageConfigVolumesBeanList,imageName);
        }

        // 5: 处理高可用信息
        ImageHighAvailabilityBean imageHighAvailabilityBean = imageDataBean.getImageHA();
        if (imageHighAvailabilityBean != null) {
            ImageHighAvailabilityBean reImageHABean = appManageService.getImageHABean(imageName);
            if (reImageHABean != null) {
                // 修改
                appManageService.editImageHA(imageHighAvailabilityBean);
            } else {
                // 新增
                appManageService.addImageHA(imageHighAvailabilityBean,imageName);
            }
        }

        // 6: 处理镜像启动参数
        List<ImageArgsBean> argsBeanList = imageDataBean.getCommandArgs();
        if (argsBeanList.size() > 0) {
            appManageService.handleImageArgs(argsBeanList,imageName);
        }

        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"设置镜像参数,成功","");
        return response;
    }


    /*
    * 删除镜像参数
    * */
    @ApiOperation(value = "删除镜像参数--接口", notes = "删除镜像参数,根据应用ID,参数类型: port,env")
    @RequestMapping(value = "/image-base/{id}/{paramType}", method = RequestMethod.DELETE)
    public VenusResponse<Object> deleteImageParam(@PathVariable("id") String id,@PathVariable("paramType") String paramType)  throws VenusException {
        if (StringUtils.isBlank(id))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "镜像参数ID为空");
        if (StringUtils.isBlank(paramType))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "参数类型为空");
        int row = appManageService.deleteImageParam(id,paramType);
        if (row == 0) {
            throw new VenusException(VenusResponseStatus.HANDLE_ERROR, "删除镜像参数异常");
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"","");
        return response;
    }


    /*
    * 部署应用
    * */
    @ApiOperation(value = "部署应用--接口", notes = "部署应用,根据选择的镜像")
    @RequestMapping(value = "/app-create/image", method = RequestMethod.POST)
    public VenusResponse<Object> depyoyApp(@RequestBody ImageDataBean imageDataBean) throws VenusException {

        String namespace = imageDataBean.getNamespace();
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT,"空间名称为空");
        String appKind = imageDataBean.getImageBase().getAppKind();
        boolean createServiceFlag = true;
        String message = "部署应用,失败";
        try {
            // 1: 先创建服务
            if (imageDataBean.getImagePortList().size() > 0) {
                createServiceFlag = appManageService.handelService(imageDataBean.getImagePortList(),imageDataBean.getImageBase().getAppNameKube(),namespace);
            }
            // 创建应用
            if (createServiceFlag) {
                boolean flag = false;
                if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1 ) {
                    flag = appManageService.deploymentApp(imageDataBean);
                } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
                    flag = appManageService.statefulSetApp(imageDataBean);
                }


                if (flag && createServiceFlag) {
                    // 记录数据到数据库
                    appManageService.addDeployApp(imageDataBean.getImageBase(),namespace);
                    message = "部署应用,成功";
                } else {
                    // 创建应用失败
                    // 删除服务
                    appManageService.deleteService(imageDataBean.getImageBase().getAppNameKube(),namespace);

                }
            }
        } catch (Exception e) {
            // 删除服务
            appManageService.deleteService(imageDataBean.getImageBase().getAppNameKube(),namespace);
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,message,"");
        return response;
    }



    /*
    * 校验应用名称,k8s里面的
    * */
    @ApiOperation(value = "验证应用名称(k8s)是否存在--接口", notes = "验证应用名称(k8s)是否存在")
    @RequestMapping(value = "/app-name-kube/{appNameKube}", method = RequestMethod.GET)
    public VenusResponse<Integer> validateAppNameKube(@PathVariable("appNameKube") String appNameKube) throws VenusException {
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        int row = appManageService.validateAppNameKube(appNameKube);
        int code = row > 0 ? VenusResponseStatus.OK : VenusResponseStatus.HANDLE_ERROR;
        VenusResponse<Integer> response = new VenusResponse<Integer>(VenusResponseStatus.OK,"",code);
        return response;
    }


    /*
    * 校验http服务域名
    * */
    @ApiOperation(value = "验证域名是否存在--接口", notes = "验证域名是否存在")
    @RequestMapping(value = "/domain-name", method = RequestMethod.GET)
    public VenusResponse<Integer> validateDomainName(@RequestParam("domainName") String domainName) throws VenusException {
        if (StringUtils.isBlank(domainName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "域名为空");
        boolean flag = appManageService.validateDomainName(domainName);
        int code = VenusResponseStatus.HANDLE_ERROR;
        if (flag) {
            code = VenusResponseStatus.OK;
        }
        VenusResponse<Integer> response = new VenusResponse<Integer>(VenusResponseStatus.OK,"",code);
        return response;
    }

    /*
    * 获得应用的服务配置
    * */
    @ApiOperation(value = "获得应用的服务配置--接口", notes = "获得应用的服务配置")
    @RequestMapping(value = "/app-config-manage", method = RequestMethod.GET)
    public VenusResponse<Object> getConfigMapByAppName(@RequestParam("namespace") String namespace,@RequestParam("appNameKube") String appNameKube ,@RequestParam("appKind") String appKind ) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(appKind))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空");

        List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();

        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) !=-1) {
            list = appManageService.getDeploymentConfigMap(namespace,appNameKube);
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",list);
        return response;
    }


    /*
    * 修改服务配置
    * */
    @ApiOperation(value = "修改应用的服务配置--接口", notes = "修改应用的服务配置")
    @RequestMapping(value = "/app-config-manage", method = RequestMethod.PATCH)
    public VenusResponse<Object> editConfigMapByAppName(@RequestBody AppConfigMapManageBean appConfigMapManageBean) throws VenusException {
        String namespace = appConfigMapManageBean.getNamespace();
        String appNameKube = appConfigMapManageBean.getAppNameKube();
        String appKind = appConfigMapManageBean.getAppKind();
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(appKind))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空");

        boolean flag = false;
        String msg = "修改服务配置,失败";
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            // 修改无状态应用的服务配置
            flag = appManageService.editDeploymentConfigMapToApp(appConfigMapManageBean);
        }


        if(flag) {
            msg = "修改服务配置,成功";
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,msg,"");
        return response;
    }

    /*
    * 新增服务配置
    * */
    @ApiOperation(value = "新增应用的服务配置--接口", notes = "新增应用的服务配置")
    @RequestMapping(value = "/app-config-manage", method = RequestMethod.POST)
    public VenusResponse<Object> addConfigMapByAppName(@RequestBody AppConfigMapManageBean appConfigMapManageBean) throws VenusException {
        String namespace = appConfigMapManageBean.getNamespace();
        String appNameKube = appConfigMapManageBean.getAppNameKube();
        String appKind = appConfigMapManageBean.getAppKind();
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(appKind))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空");

        boolean flag = false;
        String msg = "新增服务配置,失败";
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            // 修改无状态应用的服务配置
            flag = appManageService.addDeploymentConfigMapToApp(appConfigMapManageBean);
        }


        if(flag) {
            msg = "修改服务配置,成功";
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,msg,"");
        return response;
    }

    /*
    * 删除服务配置
    * */
    @ApiOperation(value = "删除应用的服务配置--接口", notes = "删除应用的服务配置")
    @RequestMapping(value = "/app-config-manage", method = RequestMethod.DELETE)
    public VenusResponse<Object> deleteConfigMapByAppName(@RequestBody AppConfigMapManageBean appConfigMapManageBean) throws VenusException {
        String namespace = appConfigMapManageBean.getNamespace();
        String appNameKube = appConfigMapManageBean.getAppNameKube();
        String appKind = appConfigMapManageBean.getAppKind();
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        if (StringUtils.isBlank(appKind))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用类型为空");

        boolean flag = false;
        String msg = "删除服务配置,失败";
        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            // 修改无状态应用的服务配置
            flag = appManageService.deleteDeploymentConfigMapToApp(appConfigMapManageBean);
        }


        if(flag) {
            msg = "删除服务配置,成功";
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,msg,"");
        return response;
    }


    /*
    * 获取自动伸缩的监控数据
    * */
    @ApiOperation(value = "获取自动伸缩的监控数据--接口", notes = "获取自动伸缩的监控数据")
    @RequestMapping(value = "/monitor-hpa", method = RequestMethod.GET)
    public VenusResponse<Object> getHPAData(@RequestParam("hpaName") String hpaName,@RequestParam("namespace") String namespace) throws VenusException{
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(hpaName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "自动伸缩资源对象名称为空");

        List<Map<String,Object>> list = appManageService.getHPAData(hpaName,namespace);


        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",list);
        return response;
    }

    /*
    * 获得服务管理数据
    * */
    @ApiOperation(value = "获得服务管理数据--接口", notes = "获得服务管理数据")
    @RequestMapping(value = "/app-service-list", method = RequestMethod.GET)
    public VenusResponse<Object> getServiceData(@RequestParam("namespace") String namespace,@RequestParam("appNameKube") String appNameKube) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        List<ImagePortBean> imagePortBeanList = appManageService.getAppService(namespace,appNameKube);
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",imagePortBeanList);
        return response;
    }

    /*
    * 获得服务管理数据 lcy 2018/4/2
    * */
    @ApiOperation(value = "根据空间获得服务数据--接口", notes = "获得服务数据")
    @RequestMapping(value = "/app-service-list/namespace", method = RequestMethod.GET)
    public VenusResponse<Object> getServiceDatas(@RequestParam("namespace") String namespace,@RequestParam("queryKey") String queryKey) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        List<ServiceBean> imagePortBeanList = appManageService.getAppServiceByNamespace(namespace);
        if(!StringUtil.isEmpty(queryKey)&&imagePortBeanList.size()>0){
            imagePortBeanList =imagePortBeanList.stream().filter(ts -> (ts.getName().indexOf(queryKey) != -1
                    || ts.getSelectors().get("app").indexOf(queryKey) != -1)).collect(Collectors.toList());
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",imagePortBeanList);
        return response;
    }


    /*
    * 获得应用端口
    * */
    @ApiOperation(value = "获得应用端口--接口", notes = "获得应用端口")
    @RequestMapping(value = "/app-service-ports", method = RequestMethod.GET)
    public VenusResponse<Object> getServicePorts(@RequestParam("namespace") String namespace,@RequestParam("appNameKube") String appNameKube,@RequestParam("appKind") String appKind) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(appNameKube))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称为空");
        List<Integer> list = new ArrayList<Integer>();

        if (AppManageConfigBean.Kind_Deployment.indexOf(appKind) != -1) {
            list = appManageService.getDeploymentPorts(namespace,appNameKube);
        } else if (AppManageConfigBean.Kind_StatefulSet.indexOf(appKind) != -1) {
            list = appManageService.getStatefulSetPorts(namespace,appNameKube);
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",list);
        return response;
    }

    /*
    * 新增应用服务
    * */
    @ApiOperation(value = "新增应用服务--接口", notes = "新增应用服务")
    @RequestMapping(value = "/app-service", method = RequestMethod.POST)
    public VenusResponse<Object> addAppService(@RequestBody ImagePortBean imagePortBean) throws VenusException {
        List<ImagePortBean> imagePortBeanList = new ArrayList<ImagePortBean>();
        imagePortBeanList.add(imagePortBean);

        boolean flag = appManageService.handelService(imagePortBeanList,imagePortBean.getAppNameKube(),imagePortBean.getNamespace());
        int code = VenusResponseStatus.OK;
        String message = "应用:" + imagePortBean.getAppNameKube() + ",新增服务,成功";
        if (!flag) {
            code = VenusResponseStatus.HANDLE_ERROR;
            message = "应用:" + imagePortBean.getAppNameKube() + ",新增服务,失败";
        }
        VenusResponse<Object> response = new VenusResponse<Object>(code,message,"");
        return response;
    }


    /*
    * 新增应用服务2 lcy 2018/4/2
    * */
    @ApiOperation(value = "新增应用服务--接口", notes = "新增应用服务")
    @RequestMapping(value = "/app-service2", method = RequestMethod.POST)
    public VenusResponse<Object> addAppService2(@RequestBody ServiceBean serviceBean) throws VenusException {
       Boolean f=appManageService.createService2(serviceBean);
       VenusResponse<Object> response =null;
       if(f) {
           response  = new VenusResponse<Object>(200,"操作成功",true);
       }else{
           response  = new VenusResponse<Object>(VenusResponseStatus.HANDLE_ERROR,"操作失败",false);
       }
        return response;
    }

    /*
    * 删除应用服务
    * */
    @ApiOperation(value = "删除应用服务--接口", notes = "删除应用服务")
    @RequestMapping(value = "/app-service/{namespace}/{serviceName}", method = RequestMethod.DELETE)
    public VenusResponse<String> deleteAppService(@PathVariable("namespace") String namespace,@PathVariable("serviceName") String serviceName) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(serviceName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用服务名称为空");
        boolean flag = appManageService.deleteServiceByName(namespace,serviceName);
        String message = "删除服务: " + serviceName + ",成功";
        if (!flag) {
            message = "删除服务: " + serviceName + ",失败";
        }

        // 删除ingress
        if (serviceName.endsWith("-http")) {
            Map<String,Object> map = appManageService.getDomainName(namespace,serviceName);
            if (map.size() > 0) {
                String id = (String) map.get("id");
                String ingressName = (String) map.get("ingress_name");
                int row = appManageService.deleteDomainNameById(id);
                if (row > 0) {
                    appManageService.deleteIngressByName(ingressName,namespace);
                }
            }
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }

    /*
    * 校验服务名称是否存在
    * */
    @ApiOperation(value = "校验服务名称是否存在--接口", notes = "校验服务名称是否存在")
    @RequestMapping(value = "/service-name", method = RequestMethod.GET)
    public VenusResponse<Integer> validateServiceName(@RequestParam("serviceName") String serviceName,@RequestParam("namespace") String namespace) throws VenusException {
        if (StringUtils.isBlank(serviceName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "服务名称为空");
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
//        String serviceName_in = serviceName + "-in";
//        String serviceName_tcp = serviceName + "-tcp";
//        String serviceName_http = serviceName + "-http";
//
//        boolean inFlag = appManageService.validateServiceName(serviceName_in,namespace);
//        boolean tcpFlag = appManageService.validateServiceName(serviceName_tcp,namespace);
//        boolean httpFlag = appManageService.validateServiceName(serviceName_http,namespace);

        boolean flag = appManageService.validateServiceName(serviceName,namespace);


        int code = VenusResponseStatus.HANDLE_ERROR;
        if (flag) {
            code = VenusResponseStatus.OK;
        }
        VenusResponse<Integer> response = new VenusResponse<Integer>(VenusResponseStatus.OK,"",code);
        return response;
    }


    /*
    * 修改应用服务的服务端口,nodePort,k8s集群节点物理主机
    * */
    @ApiOperation(value = "修改应用服务的服务端口,nodePort,k8s集群节点物理主机", notes = "修改应用服务的服务端口,nodePort,k8s集群节点物理主机")
    @RequestMapping(value = "/service/node-port", method = RequestMethod.PATCH)
    public VenusResponse<String> editAppServcieNodePort(@RequestBody ImagePortBean imagePortBean) throws VenusException {
        if (StringUtils.isBlank(imagePortBean.getServiceName()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "服务名称为空");
        if (StringUtils.isBlank(imagePortBean.getNamespace()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        boolean flag = appManageService.editAppServiceNodePort(imagePortBean);
        String msg = "修改服务:" + imagePortBean.getServiceName() + "映射端口,成功!";

        if (!flag) {
            msg = "修改服务:" + imagePortBean.getServiceName() + "映射端口,失败!";
        }

        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,msg,"");
        return response;
    }

    /*
    * 校验tcp服务绑定的端口,是否已经被使用
    * */
    @ApiOperation(value = "修改应用服务的服务端口,nodePort,k8s集群节点物理主机", notes = "修改应用服务的服务端口,nodePort,k8s集群节点物理主机")
    @RequestMapping(value = "/service/node-port/{nodePort}", method = RequestMethod.GET)
    public VenusResponse<Integer> getAppServcieNodePort(@PathVariable("nodePort") int nodePort) throws VenusException {
        List<Integer> nodePortList = appManageService.getServicePortList();
        // 过滤
        nodePortList = nodePortList.stream().filter(port -> nodePort == port).collect(Collectors.toList());
        int code = VenusResponseStatus.HANDLE_ERROR;
        if (nodePortList.size() > 0) {
            code = VenusResponseStatus.OK;
        }
        VenusResponse<Integer> response = new VenusResponse<Integer>(VenusResponseStatus.OK,"",code);
        return response;
    }

    /*
    * 修改应用服务的服务域名
    * */
    @ApiOperation(value = "修改应用服务的服务域名", notes = "修改应用服务的服务域名")
    @RequestMapping(value = "/service/domain-name", method = RequestMethod.PATCH)
    public VenusResponse<String> editAppServcieDomainName(@RequestBody ImagePortBean imagePortBean) throws VenusException {
        if (StringUtils.isBlank(imagePortBean.getIngressName()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "ingress名称为空");
        if (StringUtils.isBlank(imagePortBean.getNamespace()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");

        boolean flag = appManageService.editAppServiceDomainName(imagePortBean);

        String msg = "修改服务:" + imagePortBean.getServiceName() + ",映射域名,成功";

        if(!flag) {
            msg = "修改服务:" + imagePortBean.getServiceName() + ",映射域名,失败";
        }

        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,msg,"");
        return response;
    }

    /*
        * 获得ingress管理数据 lcy 2018/4/3
        * */
    @ApiOperation(value = "根据空间获得ingress数据--接口", notes = "获得ingress数据")
    @RequestMapping(value = "/app-ingress-list/namespace", method = RequestMethod.GET)
    public VenusResponse<Object> getIngressDatas(@RequestParam("namespace") String namespace,@RequestParam("queryKey") String queryKey) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        List<IngressBean> IngressBeans = appManageService.getIngressByNamespace(namespace);
        if(!StringUtil.isEmpty(queryKey)&&IngressBeans.size()>0){
            IngressBeans =IngressBeans.stream().filter(
                            ts -> (ts.getName().indexOf(queryKey) != -1
                            || ts.getIngressRules().stream().filter(ts1 -> (ts1.getHost().indexOf(queryKey) != -1)).collect(Collectors.toList()).size() > 0
                            || ts.getIngressRules().stream().filter(ts2 -> (
                                                                                ts2.getIngressHttpPaths().stream().filter(
                                                                                                                        ts3 ->(
                                                                                                                                ts3.getPath().indexOf(queryKey)!=-1
                                                                                                                                ||ts3.getBackend().get("serviceName").toString().indexOf(queryKey)!=-1
                                                                                                                        )
                                                                                                                    ).collect(Collectors.toList()).size()>0
                                                                            )
                                                                   ).collect(Collectors.toList()).size() > 0
                    )).collect(Collectors.toList());
        }
        VenusResponse<Object> response = new VenusResponse<Object>(VenusResponseStatus.OK,"",IngressBeans);
        return response;
    }

    /*
    * 新增/修改ingress lcy 2018/4/3
    * */
    @ApiOperation(value = "新增/修改ingress--接口", notes = "新增/修改ingress")
    @RequestMapping(value = "/app-ingress", method = RequestMethod.POST)
    public VenusResponse<Object> addAppIngress(@RequestBody IngressBean ingressBean) throws VenusException {
        Boolean f=appManageService.saveOrUpdateIngress(ingressBean);
        VenusResponse<Object> response =null;
        if(f) {
            response  = new VenusResponse<Object>(200,"新增或者修改ingress成功",true);
        }else{
            response  = new VenusResponse<Object>(VenusResponseStatus.HANDLE_ERROR,"新增或者修改ingress失败",false);
        }
        return response;
    }

    /*
    * 删除ingress lcy 2018/4/4
    * */
    @ApiOperation(value = "删除ingress--接口", notes = "删除ingress")
    @RequestMapping(value = "/app-ingress", method = RequestMethod.DELETE)
    public VenusResponse<Object> deleteAppIngress(@RequestParam("ingressName") String ingressName,@RequestParam("namespace") String namespace) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(ingressName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "ingress名称为空");
        Boolean f=appManageService.deleteIngressByName(ingressName,namespace);
        VenusResponse<Object> response =null;
        if(f) {
            response  = new VenusResponse<Object>(200,"删除ingress:"+ingressName+"成功",true);
        }else{
            response  = new VenusResponse<Object>(VenusResponseStatus.HANDLE_ERROR,"删除ingress:"+ingressName+"失败",false);
        }
        return response;
    }

    /*
    * 验证ingress name lcy 2018/4/4
    * */
    @ApiOperation(value = "验证ingress--接口", notes = "删除ingress")
    @RequestMapping(value = "/app-ingress/validateName", method = RequestMethod.GET)
    public VenusResponse<Object> validateAppIngress(@RequestParam("ingressName") String ingressName,@RequestParam("namespace") String namespace) throws VenusException {
        if (StringUtils.isBlank(namespace))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "空间名称为空");
        if (StringUtils.isBlank(ingressName))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "ingress名称为空");
        Ingress ingress=appManageService.getIngress(namespace,ingressName);
        VenusResponse<Object> response =null;
        if(ingress==null) {
            response  = new VenusResponse<Object>(200,"",true);
        }else{
            response  = new VenusResponse<Object>(VenusResponseStatus.HANDLE_ERROR,"",false);
        }
        return response;
    }



    /*
    * 设置应用基本信息  资源/启动参数/环境变量
    * */
    @ApiOperation(value = "应用基础信息维护(含资源,环境变量,启动参数等)", notes = "应用基础信息维护")
    @RequestMapping(value = "/app-base", method = RequestMethod.POST)
    public VenusResponse<String> setAppBaseInfo(@RequestBody AppBaseInfoBean appBaseInfoBean) throws VenusException {
        if (StringUtils.isBlank(appBaseInfoBean.getNamespace()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用所属空间名称为空");
        if (StringUtils.isBlank(appBaseInfoBean.getAppNameKube()))
            throw new VenusException(VenusResponseStatus.NO_CONTENT, "应用名称(k8s)为空");
        boolean flag = appManageService.setAppBaseInfo(appBaseInfoBean);
        String updateType="";
        if(appBaseInfoBean.getUpdateType()==0){
            updateType="资源配置";
        }
        if(appBaseInfoBean.getUpdateType()==1){
            updateType="启动参数";
        }
        if(appBaseInfoBean.getUpdateType()==2){
            updateType="环境变量";
        }
        String message = appBaseInfoBean.getAppName() +","+updateType+"更新失败";
        if (flag) {
            message = appBaseInfoBean.getAppName() +","+updateType+"更新成功,容器组在5秒后刷新";
        }
        VenusResponse<String> response = new VenusResponse<String>(VenusResponseStatus.OK,message,"");
        return response;
    }
}